<script setup>
import { ref, onMounted } from 'vue';
import { queryAllApi, addApi, queryAllClazzApi, queryByIdApi, updateApi, violationApi, deleteApi } from '@/api/stu'
import { ElMessage, ElMessageBox } from 'element-plus';

const genders = ref([{ name: '男', value: 1 }, { name: '女', value: 2 }])
const degrees = ref([{ name: '初中', value: 1 }, { name: '高中', value: 2 }, { name: '大专', value: 3 }, { name: '本科', value: 4 }, { name: '硕士', value: 5 }, { name: '博士', value: 6 }])
// 查询参数
const searchStu = ref({
  name: '',
  degree: '',
  clazzId: ''
})
//学生列表
const stuList = ref([]);
// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const background = ref(true)
const total = ref(0)
// 查询学员数据
const search = async () => {
  const result = await queryAllApi(searchStu.value.name, searchStu.value.degree, searchStu.value.clazzId, currentPage.value, pageSize.value);
  if (result.code) {
    stuList.value = result.data.rows;
    total.value = result.data.total;
  }
}
onMounted(() => {
  search();
  queryAllClazz();
})
const handleSizeChange = (val) => {
  search();
}
const handleCurrentChange = (val) => {
  search();
}
const clear = () => {
  searchStu.value = { name: '', degree: '', clazzId: '' };
  search();
}
// 新增学员
const dialogVisible = ref(false);
const dialogTitle = ref('');
const student = ref({
  name: '',
  no: '',
  gender: '',
  phone: '',
  idCard: '',
  isCollege: '',
  address: '',
  degree: '',
  graduationDate: '',
  clazzId: ''
})
const addStu = () => {
  dialogVisible.value = true;
  dialogTitle.value = '添加学员';
  student.value = {
    name: '',
    no: '',
    gender: '',
    phone: '',
    idCard: '',
    isCollege: '',
    address: '',
    degree: '',
    graduationDate: '',
    clazzId: ''
  }
  if (stuFormRef.value) {
    stuFormRef.value.resetFields();
  }
}
// 保存数据、修改
const save = async () => {
  if (!stuFormRef.value) return;
  stuFormRef.value.validate(
    async (valid) => {
      if (valid) {
        let result;
        if (student.value.id) {
          result = await updateApi(student.value);
        }
        else {
          result = await addApi(student.value);
        }
        if (result.code) {
          ElMessage.success('操作成功！');
          dialogVisible.value = false;
          search();
        } else {
          ElMessage.error(result.msg);
        }
      }
      else {
        ElMessage.error('请检查表单数据！');
      }
    }
  );

}
// 查询所有班级
const clazzList = ref([]);
const queryAllClazz = async () => {
  const result = await queryAllClazzApi();
  if (result.code) {
    clazzList.value = result.data;
  }
}
//表单校验规则
const rules = ref({
  name: [
    { required: true, message: '请输入学员姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度应在2到10个字符之间', trigger: 'blur' }
  ],
  no: [
    { required: true, message: '请输入学号', trigger: 'blur' },
    { len: 10, message: '学号长度必须为10位', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9]{10}$/, message: '学号只能由数字和字母组成', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' }
  ],
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { len: 18, message: '身份证号必须为18位', trigger: 'blur' },
    {
      pattern: /^[1-9]\d{5}(19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
      message: '请输入正确的身份证号',
      trigger: 'blur'
    }
  ],
  isCollege: [
    { required: true, message: '请选择是否为院校学员', trigger: 'change' }
  ]
});
const stuFormRef = ref();
// 根据id查询学员信息
const edit = async (id) => {
  const result = await queryByIdApi(id);
  if (result.code) {
    dialogVisible.value = true;
    dialogTitle.value = '编辑学员';
    student.value = result.data;
    if (stuFormRef.value) {
      stuFormRef.value.resetFields();
    }
  }
}
// 违纪处理
const dialogFormVisible = ref(false);
const handleViolation = async (id) => {
  dialogFormVisible.value = true;
  violationForm.value = { score: '' }
  violationForm.value.id = id;
  if (violationFormRef.value) {
    violationFormRef.value.resetFields();
  }
}
const violationForm = ref({
  score: '',
  id: ''
})
const submitViolation = async () => {
  if (!violationFormRef.value) return;
  violationFormRef.value.validate(
    async (valid) => {
      if (valid) {
        const result = await violationApi(violationForm.value.id, violationForm.value.score);
        if (result.code) {
          ElMessage.success('操作成功！');
          dialogFormVisible.value = false;
          search();
        } else {
          ElMessage.error(result.msg);
        }
      }
      else {
        ElMessage.error('请检查表单数据！');
      }
    }
  );

}
// 添加表单引用
const violationFormRef = ref();

// 添加校验规则
const violationRules = ref({
  score: [
    { required: true, message: '请输入违纪扣分', trigger: 'blur' },
    { pattern: /^\d+$/, message: '违纪扣分必须为数字', trigger: 'blur' }
  ]
});
// 根据id删除单个学员 ElmessageBox
const delStu = async (id) => {
  ElMessageBox.confirm(
    '您确认删除该员工吗？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      const result = await deleteApi(id);
      if (result.code) {
        ElMessage.success('删除成功！');
        search();
      } else {
        ElMessage.error(result.msg);
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除');
    })
}
// 删除多个学员
const batchDelStu = async () => {
  if (!selectedIds.value || selectedIds.value.length == 0) {
    ElMessage.info('您没有选择任何要删除的数据');
    return;
  }
  ElMessageBox.confirm(
    '您确认删除选中的' + selectedIds.value.length + '条数据吗？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      const result = await deleteApi(selectedIds.value);
      if (result.code) {
        ElMessage.success('删除成功！');
        search();
      } else {
        ElMessage.error(result.msg);
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除');
    })


}
const selectedIds = ref([]);
const handleSecelectionChange = (val) => {
  selectedIds.value = val.map(item => item.id)
}

</script>

<template>
  <h2>学员管理</h2>
  <!-- 搜索栏 -->
  <div class="container">
    <el-form :inline="true" :model="searchStu" class="demo-form-inline">
      <el-form-item label="姓名">
        <el-input v-model="searchStu.name" placeholder="请输入班级名称" clearable />
      </el-form-item>
      <el-form-item label="最高学历">
        <el-select v-model="searchStu.degree" placeholder="请选择">
          <el-option v-for="d in degrees" :key="d.value" :label="d.name" :value="d.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属班级">
        <el-select v-model="searchStu.clazzId" placeholder="请选择">
          <el-option v-for="c in clazzList" :key="c.id" :label="c.name" :value="c.id"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="search">查询</el-button>
        <el-button type="info" @click="clear">清空</el-button>
      </el-form-item>
    </el-form>
  </div>
  <!-- 功能按钮 -->
  <div class="container">
    <el-button type="primary" @click="addStu">+ 添加学员</el-button>
    <el-button type="danger" @click="batchDelStu">- 批量删除</el-button>
  </div>
  <!-- 表格列表 -->
  <div class="container">
    <el-table :data="stuList" border style="width: 100%" @selection-change="handleSecelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column prop="name" label="姓名" width="100" align="center" />
      <el-table-column prop="no" label="学号" width="150" align="center" />
      <el-table-column prop="clazzName" label="班级" width="170" align="center" />
      <el-table-column prop="gender" label="性别" width="90" align="center">
        <template #default="scope">
          {{ scope.row.gender == 1 ? '男' : '女' }}
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机号" width="150" align="center" />
      <el-table-column prop="degree" label="最高学历" width="90" align="center">
        <template #default="scope">
          <template v-if="scope.row.degree == 1">初中</template>
          <template v-if="scope.row.degree == 2">高中</template>
          <template v-if="scope.row.degree == 3">大专</template>
          <template v-if="scope.row.degree == 4">本科</template>
          <template v-if="scope.row.degree == 5">硕士</template>
          <template v-if="scope.row.degree == 6">博士</template>
        </template>
      </el-table-column>
      <el-table-column prop="violationCount" label="违纪次数" width="95" align="center" />
      <el-table-column prop="violationScore" label="违纪扣分" width="95" align="center" />
      <el-table-column prop="updateTime" label="最后操作时间" width="200" align="center" />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button type="primary" size="default" @click="edit(scope.row.id)"><el-icon>
              <Edit />
            </el-icon>编辑</el-button>
          <el-button type="warning" size="default" @click="handleViolation(scope.row.id)"><el-icon>
              <WarnTriangleFilled />
            </el-icon>违纪</el-button>
          <el-button type="danger" size="default" @click="delStu(scope.row.id)"><el-icon>
              <DeleteFilled />
            </el-icon>删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <!-- 分页条 -->
  <div class="container">
    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
      :page-sizes="[5, 10, 20, 30, 50, 75, 100]" :background="background"
      layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" />
  </div>
  <!-- 新增/修改学员的对话框 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form :model="student" label-width="80px" ref="stuFormRef" :rules="rules">
      <!-- 基本信息 -->
      <!-- 第一行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="student.name" placeholder="请输入姓名"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="学号" prop="no">
            <el-input v-model="student.no" placeholder="请输入学号"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第二行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-select v-model="student.gender" placeholder="请选择性别" style="width: 100%;">
              <el-option v-for="g in genders" :key="g.value" :label="g.name" :value="g.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="student.phone" placeholder="请输入手机号"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第三行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="身份证号" prop="idCard">
            <el-input v-model="student.idCard" placeholder="请输入身份证号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否院校" prop="isCollege">
            <el-select v-model="student.isCollege" placeholder="请选择" style="width: 100%;">
              <!-- 只能选择是或者否 -->
              <el-option label="是" value="1"></el-option>
              <el-option label="否" value="0"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第四行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="联系地址">
            <el-input v-model="student.address" placeholder="请输入联系地址"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最高学历">
            <el-select v-model="student.degree" placeholder="请选择" style="width: 100%;">
              <el-option v-for="d in degrees" :key="d.value" :label="d.name" :value="d.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第五行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="毕业时间">
            <el-date-picker v-model="student.graduationDate" type="date" style="width: 100%;" placeholder="请选择毕业时间"
              format="YYYY-MM-DD" value-format="YYYY-MM-DD"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属班级">
            <el-select v-model="student.clazzId" placeholder="请选择" style="width: 100%;">
              <el-option v-for="c in clazzList" :key="c.id" :label="c.name" :value="c.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 底部按钮 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 违纪处理对话框 -->
  <el-dialog v-model="dialogFormVisible" title="提示" width="320">
    <el-form :model="violationForm" ref="violationFormRef" :rules="violationRules">
      <div style="margin: 20px 0;">
        <p style="font-size: 14px; color: #666; margin-bottom: 15px;">请输入违纪扣分</p>
        <el-form-item prop="score">
          <el-input v-model="violationForm.score" style="width: 280px; margin: 0 auto;"
            @keyup.enter="submitViolation" />
        </el-form-item>
      </div>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitViolation">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.container {
  margin: 20px 0px;
}
</style>